import Router from 'koa-router';

import Config from '../config/config.json';
import { NOT_FOUND } from './utils/StatusError';
import * as requestParsers from './requestParsers';

import {pendingFilter} from './process';

const router = new Router();

for (const k in Config) {
  const config = Config[k];
  config.filters.forEach(filter=>{
    const conditions = [];
    if (filter.action) {
      conditions.push(info=>{
        return info.action === filter.action
      });
    }
    if (filter.reg) {
      const reg = new RegExp(filter.reg);
      conditions.push(info=>{
        return reg.test(info.name);
      });
    }
    filter.filter = info => conditions.every(v=>v(info));
  });
}

router.post('/:id', async ctx => {
  const {id} = ctx.params;
  const config = Config[id];
  if (!config) {
    throw NOT_FOUND;
  }
  const info = requestParsers[config.type](ctx.request.body, config, ctx);
  console.log(JSON.stringify(info));

  const filter = config.filters.find(v=>v.filter(info));

  ctx.body = {ok: 1};
  if (filter) {
    pendingFilter(id, filter)
      .then(v=>{
        if (__DEV__) {
          console.log('Done');
        }
      }, err=>{
        if (__DEV__) {
          console.error(err.stack);
        }
      });
  }
});

export default router;